<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class ForgotPasswordController extends Controller
{
    public function __construct()
    {
        $this->middleware('guest');
    }

    public function showLinkRequestForm()
    {
        return view('auth.passwords.mobile');
    }

    public function sendResetLinkMobile(Request $request)
    {
        if($request->getMethod()=="GET")
        {
            return view('auth.passwords.reset');
        }
        $this->validate($request, [ 'login' =>"required|string|min:4|max:15", 'captcha' => 'required|captcha'],[ 'captcha.required' => '验证码不能为空',
            'captcha.captcha' => '请输入正确的验证码']);
        $flight = User::where(username(request()->input('login')), request()->input('login'))->first();
        if($flight){

            //检查用户手机验证码状态
            $results = DB::select('select * from password_resets where mobile = :mobile', [
                'mobile' =>$flight["mobile"]
            ]);

            if($results){
                DB::delete('delete  from password_resets where mobile = :mobile', [
                    'mobile' =>$flight["mobile"]
                ]);
            }

            $randStr = str_shuffle('1234567890');
            $code = substr($randStr,0,6);
            seed_sms_code($flight["mobile"],null,  $code);
            DB::insert('insert into password_resets (mobile,token,created_at) values (?, ?,?)', [$flight->mobile,$code,date("Y-m-d H:i:s",time())]);

            if(username(request()->input('login'))!='mobile'){
                $flight->mobile=substr( $flight->mobile,0,2)."*****".substr( $flight->mobile,8,3);
            }
            session()->flash('success', '系统刚刚给您的手机号码'. $flight->mobile.'发送了一条短信验证码，请您查收。（可能会存在网络延迟）');
            return view('auth.passwords.reset');

        }else{
            session()->flash('danger', '用户名或者手机号码不存在');
            return back();
        }
    }


}
